const _ = require("lodash")
const path = require("path")
const Koa = require("koa");
const Router = require("@koa/router")
// const bodyParser = require('koa-bodyparser');
const koaBody = require("koa-body")
const error = require('koa-json-error')
const parameter = require('koa-parameter');
const requireDirectory = require("require-directory")
const static = require('koa-static')
const {port,host,baseStaticPath} = require("./config")
const app = new Koa();
//开启静态资源服务器
// app.use(static(__dirname + "/public"))


//让ctx具备访问请求体的能力: ctx.request.body
app.use(koaBody({
    multipart:true,
    formidable:{
        uploadDir:baseStaticPath,
        keepExtensions:true,
        onFileBegin(name,file){
            name = name.trim();
            let pathArr = file.path && file.path.split("\\");
            let length = pathArr.length;
            if(name === 'avatar'){
                pathArr.splice(length-1,0,"img")
            }else if(name === 'book'){
                pathArr.splice(length-1,0,"book")
            }
            file.path = pathArr.join("\\");
        }
    }
}));
//参数检验
parameter(app);
//批量注册路由器
requireDirectory(module,"./router",{
    visit:router=>{
        app.use(router.routes()).use(router.allowedMethods())
    }
});

//链接数据库
require("./db/db")

//错误处理
app.use(error({
    postFormat:(e, obj)=>{
        return  process.env.NODE_ENV === 'pro' ? _.omit(obj, 'stack') : obj
    }
}));

//起服务
app.listen(port,host,()=>{
    console.log(`server is runing on http://${host}:${port}`)
})
